import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import User from '@/views/User'
import UserEdit from '@/views/User/editUser'
import Chat from '@/views/User/Chat'
import Search from '@/views/Search'
import SearchRosult from '@/views/Search/searchRosult'
import Detail from '@/views/Detail'
import store from '@/store'
Vue.use(VueRouter)
// 解决额外bug,路由重定向问题
// 缓存原本的路由跳转方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    name: 'Layout',
    path: '/',
    component: Layout,
    children: [
      {
        name: 'Home',
        path: '',
        component: Home
      },
      {
        name: 'User',
        path: '/user',
        component: User
      }
    ]
  },
  {
    name: 'Search',
    path: '/search',
    component: Search
  },
  {
    name: 'SearchRosult',
    path: '/searchRosult',
    component: SearchRosult
  },
  {
    name: 'Detail',
    path: '/detail',
    component: Detail
  },
  {
    name: 'UserEdit',
    path: '/editUser',
    component: UserEdit
  },
  {
    name: 'Chat',
    path: '/chat',
    component: Chat
  }

]

const router = new VueRouter({
  routes
})
// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user') {
    // 验证是否有token，如果有放行，没有就跳转到login页
    const tokenInfo = store.state.tokenInfo
    if (tokenInfo && tokenInfo.token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
